<?php

declare(strict_types=1);

namespace app\admin\controller\v1;

use app\admin\model\Admin;
use app\admin\model\AdminLog;
use app\common\Backend;
use app\common\facade\Token;
use general\Random;
use PHPGangsta_GoogleAuthenticator;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Event;
use think\facade\Validate;
use think\Request;

class Index extends Backend
{
    protected $noNeedLogin      = ['logout', 'login'];
    protected $noNeedPermission = ['index'];

    public function index(): void
    {
        $adminInfo          = $this->auth->getInfo();
        $adminInfo['super'] = $this->auth->isSuperAdmin();
        unset($adminInfo['token'], $adminInfo['refresh_token']);
        $menus = $this->auth->getMenus();
        if (!$menus) {
            $this->error(('No background menu, please contact super administrator!'));
        }
        $this->success('', [
            'adminInfo'  => $adminInfo,
            'menus'      => $menus,
            'siteConfig' => [
                'siteName' => get_sys_config('site_name'),
                'version'  => get_sys_config('version'),
                'cdnUrl'   => full_url(),
                'apiUrl'   => Config::get('general.api_url'),
                'upload'   => get_upload_config(),
            ]

        ]);
    }


    //登录
    public function login(): void
    {
        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/admin/dashboard'
            ], 302);
        }
        $captchaSwitch = Config::get('general.admin_login_captcha');

        // 检查提交
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keep     = $this->request->post('keep');

            $rule = [
                'username|' . ('Username') => 'require|length:3,30',
                'password|' . ('Password') => 'require|regex:^(?!.*[&<>"\'\n\r]).{6,32}$',
            ];
            $data = [
                'username' => $username,
                'password' => $password,
            ];
            if ($captchaSwitch) {
                //验证码接收
            }
            $validate = Validate::rule($rule);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            AdminLog::setTitle(('Login'));

            $res = $this->auth->login($username, $password, (bool)$keep);

            if ($res === true) {
                $this->success(('Login succeeded!'), [
                    'userInfo'  => $this->auth->getInfo(),
                    'routePath' => '/admin/dashboard'
                ]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ?: ('Incorrect user name or password!');
                $this->error($msg);
            }
        }

        $this->success('');
    }

    //注销
    public function logout(): void
    {
        if ($this->request->isPost()) {
            $refreshToken = $this->request->post('refreshToken', '');
            if ($refreshToken) Token::delete((string)$refreshToken);
            $this->auth->logout();
            $this->success();
        }
    }

    //清理缓存
    public function clearCache()
    {
        $type = $this->request->post('type');
        if ($type == 'tp' || $type == 'all') {
            Cache::clear();
        } else {
            $this->error(('Parameter error'));
        }
        Event::trigger('cacheClearAfter', $this->app);
        $this->success(('清理成功'));
    }


    //缓存刷新
    public function refreshToken()
    {
        $refreshToken = $this->request->post('refreshToken');
        $refreshToken = Token::get($refreshToken, false);

        if (!$refreshToken || $refreshToken['expire_time'] < time()) {
            $this->error(('Login expired, please login again.'));
        }

        $newToken = Random::uuid();

        if ($refreshToken['type'] == 'admin-refresh') {
            $baToken = $this->request->server('HTTP_BATOKEN', $this->request->request('batoken', ''));
            if (!$baToken) {
                $this->error(('Invalid token'));
            }
            Token::delete($baToken);
            Token::set($newToken, 'admin', $refreshToken['user_id'], 86400);
        } elseif ($refreshToken['type'] == 'user-refresh') {
            $baUserToken = $this->request->server('HTTP_BA_USER_TOKEN', $this->request->request('ba-user-token', ''));
            if (!$baUserToken) {
                $this->error(('Invalid token'));
            }
            Token::delete($baUserToken);
            Token::set($newToken, 'user', $refreshToken['user_id'], 86400);
        }

        $this->success('', [
            'type'  => $refreshToken['type'],
            'token' => $newToken
        ]);
    }
}
